package com.rgs.base.core.util.excel;

import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ren Gaoshuai
 * @date 2022-03-08 15:45
 **/
public class FillRowWriteHandler extends AbstractRowWriteHandler {

    List<CellRangeAddress> mergedRegions;

    @Override
    public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {
        int rowTemp = rowIndex - 1;
        mergedRegions = writeSheetHolder.getCachedSheet().getMergedRegions();
        if (mergedRegions != null) {
            mergedRegions = mergedRegions.stream().filter(q -> q.getFirstRow() == rowTemp)
                    .map(q -> {
                        q.setFirstRow(q.getFirstRow() + 1);
                        q.setLastRow(q.getLastRow() + 1);
                        return q;
                    }).collect(Collectors.toList());
        }
    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        if (mergedRegions != null) {
            mergedRegions.forEach(q -> writeSheetHolder.getCachedSheet().addMergedRegion(q));
        }
    }
}
